package com.tianhui.consignortwofei.jPush;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;

import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;

import com.fgs.common.utils.LogUtil;
import com.fgs.common.utils.PackageUtil;
import com.google.gson.reflect.TypeToken;

import com.tianhui.consignortwofei.R;
import com.tianhui.consignortwofei.constant.KeyValue;
import com.tianhui.consignortwofei.mvp.model.enty.NotificationInfo;
import com.tianhui.consignortwofei.mvp.model.hetong.ContractInfo;
import com.tianhui.consignortwofei.mvp.ui.activity.MainActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.SaleCarFreightActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.SplashActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.HeTongShenPiBossActivity;
import com.tianhui.consignortwofei.mvp.ui.activity.hetong.LiuChengJieDianActivity;
import com.tianhui.consignortwofei.utils.BadgerUtil;
import com.xuexiang.xutil.net.JsonUtil;

import cn.jpush.android.api.CmdMessage;
import cn.jpush.android.api.CustomMessage;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.JPushMessage;
import cn.jpush.android.api.NotificationMessage;
import cn.jpush.android.service.JPushMessageReceiver;
import me.leolin.shortcutbadger.ShortcutBadger;

public class PushMessageReceiver extends JPushMessageReceiver {
    private static final String TAG = "PushMessageReceiver";
    private String billno;

    public static  int msgNum = 0;

    @Override
    public void onMessage(Context context, CustomMessage customMessage) {
        super.onMessage(context, customMessage);
        Log.v(TAG, "[onMessage] " + customMessage);
//        playSound(context);
//        processCustomMessage(context, customMessage);
//        LogUtil.print("customMessage", customMessage.message);
//        LogUtil.print("extra", customMessage.extra);
//        billno = customMessage.message;
    }

    @Override
    public void onNotifyMessageOpened(Context context, NotificationMessage message) {
        Log.v(TAG, "[onNotifyMessageOpened] " + message);

        try {
            String extras = message.notificationExtras;
            if (!TextUtils.isEmpty(extras)) {
                NotificationInfo info = JsonUtil.fromJson(extras, new TypeToken<NotificationInfo>() {
                }.getType());
                //打开自定义的Activity
                if (info != null) {

                    Intent intent;
                    String packageName = "com.tianhui.consignortwofei";//com.tianhui.consignor
                    int uid = PackageUtil.getPackageUid(context, packageName);
                    if (uid > 0) {//应用已安装
                        boolean isAppRunning = PackageUtil.isAppRunning(context, packageName);
                        if (isAppRunning) {
                            if ("4".equals(info.type)){
                                intent = new Intent(context, SaleCarFreightActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }else if ("5".equals(info.type)){
                                intent = new Intent(context, HeTongShenPiBossActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }else if ("6".equals(info.type)){
                                intent = new Intent(context, LiuChengJieDianActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }else {
                                intent = new Intent(context, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            }
//                            intent = new Intent(context, FindCarTuiSongActivity.class);
//                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        } else {//指定包名的程序未在运行中
                            intent = new Intent(context, SplashActivity.class);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                        }
                        Bundle bundle = new Bundle();
                        bundle.putString(KeyValue.KEY_BILLNO, info.billno);
                        bundle.putString(KeyValue.KEY_DISPATCH_NO, info.dispatchno);
                        bundle.putString(KeyValue.KEY_TYPE, info.type);
                        bundle.putString("danHao", info.code);
                        bundle.putInt("where", 2);

                        try {
                            ContractInfo mContractInfo=new ContractInfo();
                            mContractInfo.contractno=info.code;
                            bundle.putParcelable(KeyValue.KEY_CONTRACT_INFO, mContractInfo);
                        }catch (Exception e){
                            LogUtil.print(e.toString());
                        }


                        intent.putExtras(bundle);
                        context.startActivity(intent);
                    }

                }

            }

        } catch (Throwable throwable) {
            LogUtil.print(throwable.getMessage());
        }
    }

    @Override
    public void onMultiActionClicked(Context context, Intent intent) {
        Log.v(TAG, "[onMultiActionClicked] 用户点击了通知栏按钮");
        String nActionExtra = intent.getExtras().getString(JPushInterface.EXTRA_NOTIFICATION_ACTION_EXTRA);

        //开发者根据不同 Action 携带的 extra 字段来分配不同的动作。
        if (nActionExtra == null) {
            Log.d(TAG, "ACTION_NOTIFICATION_CLICK_ACTION nActionExtra is null");
            return;
        }
        if (nActionExtra.equals("my_extra1")) {
            Log.v(TAG, "[onMultiActionClicked] 用户点击通知栏按钮一");
        } else if (nActionExtra.equals("my_extra2")) {
            Log.v(TAG, "[onMultiActionClicked] 用户点击通知栏按钮二");
        } else if (nActionExtra.equals("my_extra3")) {
            Log.v(TAG, "[onMultiActionClicked] 用户点击通知栏按钮三");
        } else {
            Log.v(TAG, "[onMultiActionClicked] 用户点击通知栏按钮未定义");
        }
    }

    @Override
    public void onNotifyMessageArrived(Context context, NotificationMessage message) {
        Log.v(TAG, "[onNotifyMessageArrived] " + message);

        try {

            try {
                String extras = message.notificationExtras;
                if (!TextUtils.isEmpty(extras)) {
                    NotificationInfo info = JsonUtil.fromJson(extras, new TypeToken<NotificationInfo>() {
                    }.getType());
//                if (info != null) {
//                    String andoridsound = info.andoridsound;
//                    if ("defaultone".equals(andoridsound)){
//                        playSound(context);
//                    }
//                }

                }
            }catch (Exception e){
                LogUtil.print(e.toString());
            }


            msgNum++;
            try {
                ShortcutBadger.applyCount(context, msgNum);
            }catch (Exception e){
                LogUtil.print(e.toString());
            }

            try {
                BadgerUtil.addBadger(context, msgNum);
            }catch (Exception e){
                LogUtil.print(e.toString());
            }


        } catch (Throwable throwable) {
            LogUtil.print(throwable.getMessage());
        }

//        playSound(context);
    }

    @Override
    public void onNotifyMessageDismiss(Context context, NotificationMessage message) {
        Log.v(TAG, "[onNotifyMessageDismiss] " + message);
    }

    @Override
    public void onRegister(Context context, String registrationId) {
        Log.v(TAG, "[onRegister] " + registrationId);
    }

    @Override
    public void onConnected(Context context, boolean isConnected) {
        Log.v(TAG, "[onConnected] " + isConnected);
    }

    @Override
    public void onCommandResult(Context context, CmdMessage cmdMessage) {
        Log.v(TAG, "[onCommandResult] " + cmdMessage);
    }

    @Override
    public void onTagOperatorResult(Context context, JPushMessage jPushMessage) {
//        TagAliasOperatorHelper.getInstance().onTagOperatorResult(context,jPushMessage);
        Log.v(TAG, "onTagOperatorResult---" + jPushMessage.getErrorCode() + "");
    }

    @Override
    public void onCheckTagOperatorResult(Context context, JPushMessage jPushMessage) {
//        TagAliasOperatorHelper.getInstance().onCheckTagOperatorResult(context,jPushMessage);
        super.onCheckTagOperatorResult(context, jPushMessage);
        Log.v(TAG, "onCheckTagOperatorResult----" + jPushMessage.getErrorCode() + "");
        if (jPushMessage.getErrorCode() != 0) {
//            EventBusManage.refreshJPushCheckStatus();//刷新
        }
    }

    @Override
    public void onAliasOperatorResult(Context context, JPushMessage jPushMessage) {
//        TagAliasOperatorHelper.getInstance().onAliasOperatorResult(context,jPushMessage);
        super.onAliasOperatorResult(context, jPushMessage);
        Log.v(TAG, "onAliasOperatorResult----" + jPushMessage.getErrorCode() + "");
//        if (jPushMessage.getErrorCode() != 0) {
//            EventBusManage.refreshJPushCheckAliaStatus();
//        }
    }

    @Override
    public void onMobileNumberOperatorResult(Context context, JPushMessage jPushMessage) {
//        TagAliasOperatorHelper.getInstance().onMobileNumberOperatorResult(context,jPushMessage);
        super.onMobileNumberOperatorResult(context, jPushMessage);
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, CustomMessage customMessage) {
        Intent intent = getCertificateIntent(context, customMessage);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        NotificationManagerCompat notificationManager = NotificationManagerCompat.from(context);

//        Uri uri = Uri.parse("android.resource://com.tianhui.driverside/"+R.raw.defaultone);

        if (Build.VERSION.SDK_INT >= 26) {
            //当sdk版本大于26
            String id = "channel_1";
            String description = "143";
            int importance = NotificationManager.IMPORTANCE_LOW;
            NotificationChannel channel = new NotificationChannel(id, description, importance);
//                     channel.enableLights(true);
//                     channel.enableVibration(true);//
            notificationManager.createNotificationChannel(channel);
            Notification notification = new Notification.Builder(context, id)
                    .setCategory(Notification.CATEGORY_MESSAGE)
                    .setSmallIcon(R.mipmap.icon_app)
                    .setContentTitle(context.getResources().getString(R.string.app_name))
                    .setContentText(customMessage.message)
                    .setContentIntent(pendingIntent)
//                    .setSound(uri, null)    //设置自定义铃声
                    .setAutoCancel(true)

                    .build();
            notificationManager.notify(1, notification);
        } else {
            //当sdk版本小于26
            Notification notification = new NotificationCompat.Builder(context)
                    .setContentTitle(context.getResources().getString(R.string.app_name))
                    .setContentText(customMessage.message)
                    .setSmallIcon(R.mipmap.icon_app)
                    .setContentIntent(pendingIntent)
//                    .setSound(uri)    //设置自定义铃声
                    .setStyle(new NotificationCompat.BigTextStyle())
                    .build();
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.defaults |= Notification.DEFAULT_VIBRATE;
            notificationManager.notify(0, notification);
        }


    }

    private Intent getCertificateIntent(Context context, CustomMessage customMessage) {
//        Intent intent = new Intent(context, GoodsDetailActivity.class);
        Intent intent = new Intent(context, MainActivity.class);
        Bundle bundle = new Bundle();
        bundle.putString(KeyValue.KEY_BILLNO, customMessage.message);
        intent.putExtras(bundle);
        return intent;
    }

    @Override
    public void onNotificationSettingsCheck(Context context, boolean isOn, int source) {
        super.onNotificationSettingsCheck(context, isOn, source);
        Log.v(TAG, "[onNotificationSettingsCheck] isOn:" + isOn + ",source:" + source);
    }

    private void playSound(Context context) {
//        try{
//            MediaPlayer.create(context,R.raw.defaultone).start();
//        } catch(Exception e){
//            Log.d("MyBroadcastReceiver","Exception:"+e.toString());
//        }

    }



}
